package guigu.Map;

import guigu.Collection.User;
import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

/**
 * 向TreeMap中添加key-value,要求key必须是由同一个类创建的对象
 * 因为要按照key进行排序：自然排序、定制排序
 */
public class TreeMapTest {
    //自然排序:按姓名大小排序
    @Test
    public void test1()
    {
        TreeMap map = new TreeMap();
        User u1 = new User("Tom",18);
        User u2 = new User("Jerry",32);
        User u3 = new User("Jack",25);
        User u4 = new User("Rose",69);

        map.put(u1,98);
        map.put(u2,85);
        map.put(u3,74);
        map.put(u4,89);
        Set set2 =  map.keySet();
        Iterator iterator2 = set2.iterator();
        while (iterator2.hasNext())
        {
            Object key = iterator2.next();
            Object value = map.get(key);
            System.out.println(key+"======"+value);

        }
    }

    //定制排序：按年龄大小排序
    @Test
    public void test2()
    {
        TreeMap map = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof User && o2 instanceof User)
                {
                    User u1 = (User)o1;
                    User u2 = (User)o2;
                    return Integer.compare(u1.getAge(),u2.getAge());
                }
                else
                {
                    throw new RuntimeException("输入的类型不匹配");
                }
            }
        });
        User u1 = new User("Tom",18);
        User u2 = new User("Jerry",32);
        User u3 = new User("Jack",25);
        User u4 = new User("Rose",69);

        map.put(u1,98);
        map.put(u2,85);
        map.put(u3,74);
        map.put(u4,89);
        Set set2 =  map.keySet();
        Iterator iterator2 = set2.iterator();
        while (iterator2.hasNext())
        {
            Object key = iterator2.next();
            Object value = map.get(key);
            System.out.println(key+"======"+value);

        }
    }
}
